﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Cwt;
using SmartSpace.Core;
using System.Text;

namespace WebApp.Parts
{
    public partial class ArticleListPart : System.Web.UI.UserControl
    {
        public string CagetoryCode { get; set; }

        private PagedList<Article> Source { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int pageIndex = 0;
                try
                {
                    pageIndex = Convert.ToInt32(Request.QueryString["p"]);
                    if (pageIndex > 0)
                    {
                        pageIndex--;
                    }
                }
                catch
                {
                    pageIndex = 0;
                }

                int limit = 4;
                int start = pageIndex * limit;
                ICwtService service = Global.Get<ICwtService>();
                Category category = service.FindCategory(this.CagetoryCode);
                if (category != null)
                {
                    this._ctlHeadCategory.InnerText = category.Caption;
                    Source = service.FindArticles(category.Id, start, limit);
                    this._ctlRepeater.DataSource = Source;
                    this._ctlRepeater.DataBind();
                }
            }
        }

        public string GetStart()
        {
            if (Source == null)
            {
                return string.Empty;
            }
            int pageIndex = Source.Start/Source.Limit;
            pageIndex++;
            return string.Format("第{0}页", pageIndex);
        }

        public string GetPageLink()
        {
            if (Source == null)
            {
                return string.Empty;
            }

            int pageIndex = Source.Start / Source.Limit;

            StringBuilder builder = new StringBuilder();
            for (int index = 0; index * Source.Limit < Source.Total; index++)
            {
                if (pageIndex == index)
                {
                    builder.AppendFormat("<span>{0}</span>", index + 1);
                }
                else
                {
                    builder.AppendFormat("<a href='?p={0}'>{0}</a>", index + 1);
                }
            }
            return builder.ToString();
        }
    }
}